package showcase

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/ctxdatax"
	"mall/common/enumx"
	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateShowcaseLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateShowcaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateShowcaseLogic {
	return &UpdateShowcaseLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateShowcaseLogic) UpdateShowcase(req *types.UpdateShowcaseReq) (resp *types.UpdateShowcaseResp, err error) {
	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	desc := strings.TrimSpace(req.Desc)
	background := strings.TrimSpace(req.Background)
	pattern := strings.TrimSpace(req.Pattern)
	frame := strings.TrimSpace(req.Frame)

	newThumbMap := make(map[int64]*types.ForumMedia)
	var newMediaIds []string
	var newAttachmentIds []string
	var thumbnail int32 = 1
	var newMedia []*forumclient.ForumMedia
	if len(req.Photos) > 0 {
		for _, m := range req.Photos {
			if m.Id > 0 {
				if _, exist := newThumbMap[m.Id]; !exist { // 忽略重复id
					newThumbMap[m.Id] = m
					newMediaIds = append(newMediaIds, strconv.FormatInt(m.Id, 10))
				}
			}
		}
	}
	// 根据 newMediaIds 查询 attachments 记录到 forum_attachment_relationships
	if len(newMediaIds) > 0 {
		res, err := l.svcCtx.AttachmentRpc.BackendGetFileList(l.ctx, &attachmentclient.FileListReq{
			Ids: pointy.GetPointer(strings.Join(newMediaIds, ",")),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			for _, v := range res.List {
				var mediaId int64
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil && i > 0 {
					mediaId = i
				}
				var url string
				if v.Url != nil && len(*v.Url) > 0 {
					url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.StaticUrl, *v.Url)
				}
				var uri string
				if v.Path != nil && len(*v.Path) > 0 {
					uri = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.ProxyUrl, *v.Path)
				}
				if len(url) == 0 {
					url = uri
				}

				if media, ok := newThumbMap[mediaId]; ok {
					newMedia = append(newMedia, &forumclient.ForumMedia{
						AltText:   media.AltText,
						Id:        mediaId,
						Uid:       media.Uid,
						Meta:      media.Details,
						Order:     media.Order,
						Thumbnail: thumbnail,
						Uri:       media.Url,
						Url:       url,
					})
					newAttachmentIds = append(newAttachmentIds, *v.Id)
				}
			}
		}
	}

	_, err = l.svcCtx.ForumRpc.UpdateShowcase(l.ctx, &forumclient.UpdateShowcaseReq{
		UserId:     int64(userId),
		PlatformId: int32(enumx.ThirdPartyPlatformWechatMini),
		Desc:       desc,
		Background: background,
		Pattern:    pattern,
		Frame:      frame,
		NewMedia:   newMedia,
	})
	if err != nil {
		return
	}

	if len(newAttachmentIds) > 0 {
		_, err = l.svcCtx.AttachmentRpc.BackendCreateLog(l.ctx, &attachmentclient.CreateLogReq{
			FileIds:    newAttachmentIds,
			UserId:     pointy.GetPointer(strconv.FormatInt(int64(userId), 10)),
			Put:        pointy.GetPointer(uint32(1)),
			ObjectId:   pointy.GetPointer(userId),
			ObjectType: pointy.GetPointer(uint32(globalkey.AttachmentLogTypeWardrobe)),
			Title:      pointy.GetPointer("wardrobe"),
		})
		if err != nil {
			logx.Errorw("forum UpdateShowcase AttachmentRpc BackendCreateLog err", logx.Field("detail", err.Error()))
		}
	}

	return &types.UpdateShowcaseResp{
		Status:  "ok",
		Message: "操作成功",
	}, nil
}
